package com.sccomsumer.comsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class RestTemplateController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient lb;


    /**
     * 注意如果单纯得使用restTemplate。主机地址部分，必须需要填写ip地址和端口，
     * 不能使用服务名称
     * * @return
     */
    @GetMapping("/getHi")
    public String getHi() {

        String url ="http://provider/getHi";
        //在RestTemplate配置中加了@loadbalance
//        String url = "http://localhost:9010/getHi";
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    @GetMapping("/getHi2")
    public String getHiUseRibbin() {

        ServiceInstance instance = lb.choose("PROVIDER");

//        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/getHi";
        String url = "http://provider/getHi";
//        System.out.println(url);
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    /**
     * hystrix的使用
//     */
//    public  String testHystrix(){
//
//    }
}
